let express = require('express');
let router = express.Router();
let errorTypes = require('../utils/error-types');
let _db = require('../utils/db');

/**
 * @api {get} /appliance/typelist 获取家电类型列表
 */
router.get('/typelist', function (req, res, next) {
    _db.query(`
    SELECT * FROM appliance_type;
    `)
        .then(function (result) {
            res.sendResolve(result);
        })
        .catch(function (err) {
            return res.send(errorTypes.DB_INTERNAL_ERROR(err));
        });
});

/**
 * @api {get} /appliance/list 获取家电列表
 */
router.get('/list', function (req, res, next) {
    let userid = req.session.userid;
    if (!userid) {
        return res.send(errorTypes.UNAUTHORIZED());
    }

    _db.query(`
    SELECT   
    user_fan.id AS id,   
    user_fan.start_time,
    user_fan.name AS name,
    appliance_type.id AS type_id,
    appliance_type.name AS type_name,   
    appliance_type.power AS power
        FROM
    user_fan  
        JOIN
    appliance_type ON user_fan.fk_fan_id = appliance_type.id  
        WHERE  
    user_fan.fk_user_id = ?;
    `, [userid])
        .then(function (result) {
            let dataresult = result.map(item => {
                return {
                    id: item.id,
                    type_id: item.type_id,
                    type_name: item.type_name,
                    name: item.name,
                    power: item.power,
                    start_time: item.start_time,
                    status: item.start_time ? 1 : 0
                }
            });

            res.sendResolve(dataresult);
        })
        .catch(function (err) {
            return res.send(errorTypes.DB_INTERNAL_ERROR(err));
        });
});

/**
 * @api {get} /appliance/info 获取家电信息
 */
router.get('/info', function (req, res, next) {
    let userid = req.session.userid;
    let { id } = req.query;
    if (!userid) {
        return res.send(errorTypes.UNAUTHORIZED());
    }

    if (!id) {
        return res.send(errorTypes.ILLEGAL_ARGUMENT("家电id不能为空"));
    }

    _db.query(`
    SELECT   
    user_fan.id AS id,   
    user_fan.start_time,
    user_fan.name AS name,
    appliance_type.id AS type_id,
    appliance_type.name AS type_name,   
    appliance_type.power AS power
        FROM
    user_fan  
        JOIN
    appliance_type ON user_fan.fk_fan_id = appliance_type.id  
        WHERE  
    user_fan.fk_user_id = ? AND user_fan.id = ?;
    `, [userid, id])
        .then(function (result) {
            if (result.length == 0) {
                return res.send(errorTypes.ILLEGAL_ARGUMENT("家电不存在"));
            }

            let dataresult = result.map(item => {
                return {
                    id: item.id,
                    type_id: item.type_id,
                    type_name: item.type_name,
                    name: item.name,
                    power: item.power,
                    start_time: item.start_time,
                    status: item.start_time ? 1 : 0
                }
            });

            res.sendResolve(dataresult[0]);
        })
        .catch(function (err) {
            return res.send(errorTypes.DB_INTERNAL_ERROR(err));
        });
});


/**
 * @api {post} /appliance/add 添加家电
 */
router.post('/add', function (req, res, next) {
    let userid = req.session.userid;
    let { type_id, name = "default" } = req.body;
    if (!userid) {
        return res.send(errorTypes.UNAUTHORIZED());
    }

    if (!type_id) {
        return res.send(errorTypes.ILLEGAL_ARGUMENT("家电类型id不能为空"));
    }

    _db.query(`
    SELECT * FROM appliance_type WHERE id = ?;
    `, [type_id])
        .then(function (result) {
            if (result.length == 0) {
                return res.send(errorTypes.ILLEGAL_ARGUMENT("家电类型不存在"));
            }

            _db.query(`
            INSERT INTO user_fan (fk_user_id, fk_fan_id, name)
            VALUES (?, ?, ?);
            `, [userid, type_id, name])
                .then(function (result) {
                    rows = result.affectedRows;
                    if (rows == 0) {
                        return res.send(errorTypes.DB_NOT_CHANGED());
                    }
                })
            res.sendResolve();
        })
        .catch(function (err) {
            return res.send(errorTypes.DB_INTERNAL_ERROR(err));
        });
});

/**
 * @api {post} /appliance/poweron 开启家电
 */
router.post('/poweron', function (req, res, next) {
    let userid = req.session.userid;
    let { id } = req.body;
    if (!userid) {
        return res.send(errorTypes.UNAUTHORIZED());
    }

    if (!id) {
        return res.send(errorTypes.ILLEGAL_ARGUMENT("家电id不能为空"));
    }

    _db.query(`
    SELECT * FROM user_fan WHERE id = ?;
    `, [id])
        .then(function (result) {
            if (result.length == 0) {
                return res.send(errorTypes.ILLEGAL_ARGUMENT("家电不存在"));
            }

            _db.query(`
            UPDATE user_fan SET start_time = NOW() WHERE id = ?;
            `, [id])
                .then(function (result) {
                    rows = result.affectedRows;
                    if (rows == 0) {
                        return res.send(errorTypes.DB_NOT_CHANGED());
                    }
                })
            res.sendResolve();
        })
        .catch(function (err) {
            return res.send(errorTypes.DB_INTERNAL_ERROR(err));
        });
});

/**
 * @api {post} /appliance/poweroff 关闭家电
 */
router.post('/poweroff', function (req, res, next) {
    let userid = req.session.userid;
    let { id } = req.body;
    if (!userid) {
        return res.send(errorTypes.UNAUTHORIZED());
    }

    if (!id) {
        return res.send(errorTypes.ILLEGAL_ARGUMENT("家电id不能为空"));
    }

    _db.query(`
    SELECT user_fan.*, appliance_type.power
    FROM user_fan
    INNER JOIN appliance_type ON user_fan.fk_fan_id = appliance_type.id
    WHERE user_fan.id = ?;
    `, [id])
        .then((result) => {
            if (result.length == 0) {
                return res.send(errorTypes.ILLEGAL_ARGUMENT("家电不存在"));
            }
            if (!result[0].start_time) {
                return res.send(errorTypes.ILLEGAL_ARGUMENT("家电已经关闭"));
            }

            const appliance = result[0];
            const power = appliance.power; // power per second
            const startTime = new Date(appliance.start_time);
            const currentTime = new Date();
            const seconds = (currentTime - startTime) / 1000; // in seconds
            const elapsedTime = seconds / (60 * 60); // in hours
            console.log(`[appliance poweroff]${(currentTime - startTime)} // power: ${power}, startTime: ${startTime}, currentTime: ${currentTime}, elapsedTime: ${elapsedTime}`);
            const powerConsumed = power * elapsedTime || 0;

            return Promise.all([
                _db.query('UPDATE user_fan SET start_time = NULL WHERE id = ?;', [id]),
                _db.query('UPDATE user SET remain = GREATEST(0, remain - ?) WHERE id = ?;', [powerConsumed, userid])
            ])
            .then(() => {
                res.sendResolve({
                    startTime: startTime,
                    endTime: currentTime,
                    seconds: seconds.toFixed(0), // 消费时间(小时)
                    powerConsumed: powerConsumed.toFixed(3) // 返回消费电量
                });
            });
        })
        .catch((err) => {
            res.send(errorTypes.DB_INTERNAL_ERROR(err));
        });
});

module.exports = router;
